from rest_framework import serializers

from .models import BookInfo,HeroInfo


class BookInfoModelSerializer(serializers.ModelSerializer):
    """图书数据序列化器"""
    class Meta:
        model = BookInfo
        # 设置反序列化全部
        # fields = '__all__'
        # 设置反序列化可以显示的部分
        # fields = ['id','btitle','bpub_date']
        #设置排除某个不显示
        # exclude = ('image',)
        fields = ('id','btitle','bpub_date','bread','bcomment')#设定只读字段
        #设置阅读量和评论量最小值为0
        extra_kwargs = {
            'bread':{'min_value':0,'required':True},
            'bcomment':{'min_value':0,'required':True},
        }


class HeroInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = HeroInfo
        fields = ['id', 'hname', 'hbook']
        depth = 1


def about_django(value):
    if 'django' not in value.lower():
        raise serializers.ValidationError("图书不是关于django的")

class BookInfoSerializer(serializers.Serializer):
    """图书数据序列化器"""
    id = serializers.IntegerField(label='ID', read_only=True)
    btitle = serializers.CharField(label='名称', max_length=20,validators=[about_django])
    bpub_date = serializers.DateField(label='发布日期', required=False)
    bread = serializers.IntegerField(label='阅读量', required=False)
    bcomment = serializers.IntegerField(label='评论量', required=False)
    image = serializers.ImageField(label='图片', required=False)

    #     定义一关联多的序列化器字段
    #     many=True：表示一对多
    heroinfo_set = serializers.StringRelatedField(label='图书',read_only=True)

#     def validate_btitle(self,value):
# #         单个字段的验证
#         if 'django' not in value.lower():
#             raise serializers.ValidationError("图书不是关于django的")
#         return value
    """多自段的联合验证"""
    def validate(self, attrs):
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if bread < bcomment:
            raise serializers.ValidationError('阅读量小于评论量')
        return attrs

    def create(self, validated_data):
        """新建"""

        return BookInfo.objects.create(**validated_data)
    # Django框架基础DRF - day02

    def update(self, instance, validated_data):
        """更更新,instance为要更更新的对象实例例"""

        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance




# 关联对象嵌套序列化
class HeroInfoSerializer(serializers.Serializer):
#     英雄数据序列化
    GENDER_CHOICES = (
        (0,'male'),
        (1,'female')
    )
    id = serializers.IntegerField(label='ID',read_only=True)
    hname = serializers.CharField(label='名字',max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES,label='性别',required=False)
    hcomment = serializers.CharField(label='描述信息',max_length=200,required=False,allow_null=True)

    # hbook = serializers.StringRelatedField(label='图书',read_only=True)
    hbook = BookInfoSerializer()



